import { IUserAddOrEditPosLeft } from '../type';
import React, { ChangeEvent, useCallback, useContext, useMemo } from 'react';
import { AutoComplete, Card, Col, Empty, Input, Tooltip, Tree } from 'antd';
import { UserManageContext, UserOtherHandleContext } from '../hooks';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { SearchOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';
import MyIcon from '@/components/MyIcon';
import { loopArray, transltateFn } from '@/utils';

export const UserAddOrEditPosLeft: React.FC<IUserAddOrEditPosLeft> = () => {
  const { leftTreeData } = useContext(UserManageContext);
  const {
    secopeLeftSearValue,
    userOthDispatch,
    twoLeftExpandedKeys,
    twoAutoExpandParent,
    twoLeftSelectKeys,
  } = useContext(UserOtherHandleContext);

  // 渲染树数据  Tree
  const orgTreeData = (data: any[]): any[] => {
    let disabled: boolean = false;
    return data?.map((item) => {
      const name = item?.name ?? item?.text;
      const nameLength = name?.length;
      const select = name?.search(secopeLeftSearValue);
      const searchLength = secopeLeftSearValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = secopeLeftSearValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {afterStr}
              <span style={{ color: '#f50' }}>{selectStr}</span>
              {beforeStr}
            </span>
          </Tooltip>
        ) : (
          <Tooltip title={name}>
            <span className={pageStyles['over-flow-hidden']}>
              {item?.name ?? item?.text ?? '--'}
            </span>
          </Tooltip>
        );
      // 判断树节点复选框是否可选
      if (item?.textType == 2 && item?.open == true) {
        disabled = false;
      } else {
        disabled = true;
      }

      if (item?.children) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
              }}
              id={item?.id + 'userCardLeft'}
            >
              {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
              {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
              {item?.textType == 2 && (
                <MyIcon type={'icon-icon_lingdaopishi'} />
              )}
              &nbsp;
              {titleTree}
            </div>
          ),
          key: item?.id,
          children: orgTreeData(item?.children),
          disabled: disabled,
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              // paddingRight: 20,
            }}
            id={item?.id + 'userCardLeft'}
          >
            {item?.textType == 0 && <MyIcon type={'icon-bank'} />}
            {item?.textType == 1 && <MyIcon type={'icon-cluster'} />}
            {item?.textType == 2 && <MyIcon type={'icon-icon_lingdaopishi'} />}
            &nbsp;
            {titleTree}
          </div>
        ),
        key: item?.id,
        disabled: disabled,
      };
    });
  };

  // 搜索下拉菜单
  const autoOptionLeft = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if ((item?.name || item?.text)?.includes(secopeLeftSearValue)) {
          // const name = item?.name || item?.text;
          // const nameLength = name?.length;
          // const select = name?.search(secopeLeftSearValue);
          // const searchLength = secopeLeftSearValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = secopeLeftSearValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name || item?.text,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
            itemrowobj: { ...item },
          });
        }
      });
    };
    tileTreeData(leftTreeData);
    return option;
  }, [leftTreeData, secopeLeftSearValue]);

  // 点击搜索
  const onAutoSelectLeft = (value: string, option: any) => {
    // const promise = new Promise((resolve) => {
    const optionId = option?.key;
    const rowObj = option?.itemrowobj;
    const targetNode = loopArray(leftTreeData); //平铺的树
    let openTreeIds = transltateFn(targetNode, rowObj?.pID);

    userOthDispatch({
      type: 'otherHandle-twoAutoExpandParent',
      payload: true,
    });
    userOthDispatch({
      type: 'otherHandle-twoLeftExpandedKeys',
      payload: openTreeIds,
    });

    userOthDispatch({
      type: 'otherHandle-secopeLeftSearValue',
      payload: value,
    });

    setTimeout(() => {
      scrollToAnchor(optionId);
    }, 1000);

    //   resolve(optionId);
    // });
    // promise.then(() => {
    // });
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    userOthDispatch({
      type: 'otherHandle-secopeLeftSearValue',
      payload: e.target.value,
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id + 'userCardLeft');
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 点击展开关闭树
  const onTreeExpand = useCallback(
    (e, a) => {
      userOthDispatch({
        type: 'otherHandle-twoLeftExpandedKeys',
        payload: e,
      });
      userOthDispatch({
        type: 'otherHandle-twoAutoExpandParent',
        payload: false,
      });
    },
    [twoLeftSelectKeys],
  );

  // 保存选中的值
  const onTreeSelect = (checkedKeys: any, treeNodes: any) => {
    userOthDispatch({
      type: 'otherHandle-twoLeftSelectKeys',
      payload: checkedKeys?.checked,
    });
    userOthDispatch({
      type: 'otherHandle-twoLeftSelectRows',
      payload: treeNodes?.checkedNodes,
    });
  };

  return (
    <>
      <Col span={11}>
        <Card
          bordered
          title={
            <>
              <AutoComplete
                style={{ width: '100%' }}
                options={autoOptionLeft}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                onSelect={onAutoSelectLeft}
              >
                <Input
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  placeholder="请按名称搜索"
                  allowClear
                />
              </AutoComplete>
            </>
          }
        >
          <ScrollBarLayout
            style={{
              height: document.body.clientHeight * 0.4,
              padding: '10px 0px',
            }}
          >
            {leftTreeData && leftTreeData?.length > 0 ? (
              <Tree
                treeData={orgTreeData(leftTreeData)}
                blockNode={true}
                checkable={true}
                autoExpandParent={twoAutoExpandParent}
                onCheck={onTreeSelect}
                checkedKeys={twoLeftSelectKeys}
                expandedKeys={twoLeftExpandedKeys}
                onExpand={onTreeExpand}
                checkStrictly={true}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </ScrollBarLayout>
        </Card>
      </Col>
    </>
  );
};
